package net.imagine.frontend.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.imagine.provider.skyline.BaseDispatchAction;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

/**
 * Servlet implementation class SwfUploadServlet
 */
public class SwfUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 8143434173541206819L;
	private static final Log logger = LogFactory.getLog(SwfUploadServlet.class);
	private transient CommonsMultipartResolver multipartResolver;
	
	private transient BaseDispatchAction action = new BaseDispatchAction(); 

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SwfUploadServlet() {
		super();
	}

	@Override
	public void init() throws ServletException {
		super.init();
		initUploadConfig();
	}

	private void initUploadConfig() {
		String parameter = getInitParameter("method");
		WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
		multipartResolver = (CommonsMultipartResolver) ctx.getBean("multipartResolver");
		Object action = ctx.getBean("uploadAction");
		this.action.setParameter(parameter);
		this.action.setActionInstance(action);
		this.action.setClazz(action.getClass());
	}

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		if(multipartResolver.isMultipart(request)) {
			request = multipartResolver.resolveMultipart(request);
		} 
		try {
			action.execute(request, response);
		} catch (Exception e) {
			logger.warn("执行发生错误",e);
			throw new RuntimeException(e);
		}
		
		if(multipartResolver.isMultipart(request)) {
			multipartResolver.cleanupMultipart((MultipartHttpServletRequest) request);
		}
	}

}
